<template>
  <div class="login-container">
    <van-nav-bar title="登录" class="my-nav-bar" />
    <van-form @submit="onSubmit">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="输入手机号"
        required
        :rules="[
          { required: true, message: '请输入手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机格式不对'
          }
        ]"
      />
      <!-- 通过 validator 进行函数校验 -->
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="输入验证码"
        required
        :rules="[
          { required: true, message: '请输入验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userlogin } from '../../api/login'
import { saveToken } from '../../utils/token'
export default {
  name: 'login',
  data () {
    return {
      mobile: '',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isLoading = true
      userlogin(values)
        .then(res => {
          saveToken(res.data.data)
          this.$toast.success('登录成功')
          this.isLoading = false
          const redirect = this.$route.query.redirect
          if (redirect) {
            return this.$router.push({ path: redirect })
          }
          this.$router.push({ path: '/index' })
        })
        .catch(errorRes => {
          this.$toast.fail('登录失败')
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .my-nav-bar {
    background-color: #1989fa;
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
